package com.expdatacloud.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 通过切面获取cookie来切换数据源
 * @author jie
 * @date 2019/10/29 -14:17
 */
@Aspect
@Order(1)// 保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {

    @Around("execution(* com.expdatacloud.controller..*(..))")
    public Object switchDS(ProceedingJoinPoint point) throws Throwable {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        Object library = null;
        Cookie[] cookies =  request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if("library".equals(cookie.getName())){
                    library =  cookie.getValue();
                }
            }
        }

        //默认数据源
        String dataSource = "DSA";
        if(library != null){
            if("WMWHSE2".equals(library.toString())){
                dataSource = "DSB";
            }
        }
        // 切换数据源
        DataSourceHolder.setDataSource(dataSource);

        try {
            return point.proceed();
        } finally {
            DataSourceHolder.clearDataSource();
        }
    }
}
